"""
cnblogs.com login service

:Author: Sereyna
"""
import requests
import undetected_chromedriver as uc
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.remote.webdriver import By
from fake_useragent import UserAgent

import time


class CnblogsLoginService:
    webname = 'cnblogs'
    login_url = "https://account.cnblogs.com/signin"

    def __init__(self, settings):
        self.username = settings.Accounts[self.webname]['USERNAME']
        self.password = settings.Accounts[self.webname]['PASSWORD']
        browser_options = Options()
        browser_options.headless = True  # 无界面启动driver
        self.browser = uc.Chrome(options=browser_options)  # 生成驱动（去官网下载最新版）
        self.ua = UserAgent()

    def check_login(self):
        pass

    def check_cookie(self, cookie_dict):
        res = requests.get("https://news.cnblogs.com/n/771655/", headers={
            "User-Agent": self.ua.random
        }, cookies=cookie_dict, allow_redirects=False)
        if res.status_code != 200:
            return False
        else:
            return True

    def login(self):
        print(f"正在访问{self.webname}登录页面: {self.login_url}")
        self.browser.get(self.login_url)  # 登录页面
        time.sleep(2)  # 防止某些元素加载太慢

        # 自动输入用户名、密码
        print("正在自动输入用户名和密码")
        username_input = self.browser.find_element(By.XPATH, '//*[@id="mat-input-0"]')
        password_input = self.browser.find_element(By.XPATH, '//*[@id="mat-input-1"]')
        username_input.send_keys(self.username)
        password_input.send_keys(self.password)

        print("正在进行智能验证")
        login_button = self.browser.find_element(By.XPATH, '//*[contains(@class, "action-button")]')
        login_button.click()  # 只有点一下这个才会出现智能验证

        # 自动化点击智能识别按钮
        self.browser.execute_script("Object.defineProperties(navigator,{webdriver:{get:()=>undefined}})")  # 破解智能验证
        verify_button = self.browser.find_element(By.XPATH, '//*[contains(@id, "aliyun_captcha")]')
        verify_button.click()

        print("验证完成")
        time.sleep(30)  # 歇一下，不要太快进行
        print("间隔30秒完成，获取cookies")
        cookies = self.browser.get_cookies()  # 登录成功后拿到cookie
        cookies_dict = {}
        for cookie in cookies:
            cookies_dict[cookie["name"]] = cookie["value"]

        self.browser.close()
        return cookies_dict

# if __name__ == "__main__":
#     import settings
#     cnblogs = CnblogsLoginService(settings)
#     cookie_dict = cnblogs.login()
#     print(f"\n返回的cookie：{cookie_dict}\n")
#     ua = UserAgent()
#
#     headers = {
#         "User-Agent": ua.random
#     }
#     rsp = requests.get("https://news.cnblogs.com/n/771655/", headers=headers, cookies=cookie_dict, allow_redirects=False)
#     print(f"\n返回状态码：{rsp.status_code}\n")
